import 'dart:io';
import 'package:permission_handler/permission_handler.dart';
import 'package:device_info_plus/device_info_plus.dart';

class PermissionService {
  static Future<bool> requestStoragePermission() async {
    if (Platform.isAndroid) {
      final deviceInfo = DeviceInfoPlugin();
      final androidInfo = await deviceInfo.androidInfo;
      final sdkInt = androidInfo.version.sdkInt;

      if (sdkInt >= 33) {
        // Android 13+ 请求媒体权限
        final Map<Permission, PermissionStatus> statuses = await [
          Permission.photos,
          Permission.videos,
          Permission.audio,
        ].request();

        return statuses.values.every((status) => status.isGranted);
      } else if (sdkInt >= 30) {
        // Android 11-12 请求管理外部存储权限
        final status = await Permission.manageExternalStorage.request();
        if (status.isGranted) {
          return true;
        }
        // 如果管理权限被拒绝，尝试普通存储权限
        final normalStatus = await Permission.storage.request();
        return normalStatus.isGranted;
      } else {
        // Android 10 及以下请求存储权限
        final status = await Permission.storage.request();
        return status.isGranted;
      }
    }

    // 非Android平台
    return true;
  }

  static Future<void> openAppSettingsIfPermissionDenied() async {
    final status = await Permission.storage.status;
    if (status.isPermanentlyDenied) {
      await openAppSettings();
    }
  }
}
